<template>
  <PasswordDrawer v-model="pwdDrawerVisible" />
  <el-dropdown trigger="click">
    <div class="avatar">
      <img :src="avatar" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <!-- <el-dropdown-item @click="openDialog('infoRef')">
          <el-icon><User /></el-icon>个人信息
        </el-dropdown-item> -->
        <el-dropdown-item @click="updatePassword">
          <el-icon><Edit /></el-icon>修改密码
        </el-dropdown-item>
        <el-dropdown-item @click="logoutBtnClick" divided>
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <!-- infoDialog -->
  <InfoDialog ref="infoRef"></InfoDialog>
  <!-- passwordDialog -->
  <PasswordDialog ref="passwordRef"></PasswordDialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { getBasePath } from '@/utils'
import InfoDialog from './InfoDialog.vue'
import PasswordDialog from './PasswordDialog.vue'
import PasswordDrawer from '@/layouts/components/PasswordDrawer/index.vue'
import { logout } from '@/utils/token'
import { toPortal } from '@/utils/redirect'
import { useTabsStore } from '@/stores/modules/tabs'
import { useUserStore } from '@/stores/modules/user'
import { ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'

const pwdDrawerVisible = ref(false)
const updatePassword = () => {
  pwdDrawerVisible.value = true
}
const userStore = useUserStore()
const tabStore = useTabsStore()
const avatar = computed(() => {
  return userStore.userInfo?.avatar ? userStore.userInfo.avatar : getBasePath() + '/images/avatar.png'
})
// 打开修改密码和个人信息弹窗
const infoRef = ref<InstanceType<typeof InfoDialog> | null>(null)
const passwordRef = ref<InstanceType<typeof PasswordDialog> | null>(null)
// const openDialog = (ref: string) => {
//   if (ref == 'infoRef') infoRef.value?.openDialog()
//   if (ref == 'passwordRef') passwordRef.value?.openDialog()
// }
async function logoutBtnClick() {
  ElMessageBox.confirm('请选择方式?', '温馨提示', {
    distinguishCancelAndClose: true,
    confirmButtonText: '退出登录',
    cancelButtonText: '返回门户',
    type: 'warning'
  })
    .then(async () => {
      await tabStore.closeMultipleTab()
      logout(true)
    })
    .catch((action: Action) => {
      if (action === 'cancel') {
        toPortal()
      }
    })
}
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
